package com.sos.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sos.entity.LayuiR;
import com.sos.entity.po.Account;
import com.sos.entity.po.Doctor;
import com.sos.mapper.AccountMapper;
import com.sos.mapper.DoctorMapper;
import com.sos.service.AccountService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author 港某人
 * @date 2021/3/19 16:20
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Object> implements AccountService {

    @Resource
    DoctorMapper doctorMapper;

    private static final String S = "200645049";

    @Override
    public LayuiR<Boolean> login(Account account) {
        Account accountById = baseMapper.getAccountById(account.getAccount());
        if (accountById == null) {
            return LayuiR.data(false, "账号不存在");
        }
        if (!account.getPassword().equals(accountById.getPassword())) {
            return LayuiR.data(false, "密码错误");
        }
        if (!"doctor".equals(accountById.getRole())) {
            return LayuiR.data(false, "角色不正确");
        }
        Doctor doctor = doctorMapper.getDoctorByAccount(account.getAccount());
        String sign = JWT.create()
                .withClaim("id", doctor.getObjId())
                .withClaim("account", doctor.getAccount())
                .withClaim("name", doctor.getName())
                .withIssuedAt(new Date())
                //12小时
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 12))
                .sign(Algorithm.HMAC256(S));
        return LayuiR.data(true, sign);
    }

    @Override
    public LayuiR<Boolean> register(Account account) {
        Account accountById = baseMapper.getAccountById(account.getAccount());
        if (accountById != null) {
            return LayuiR.data(false, "账号已存在");
        }
        account.setRole("doctor");
        baseMapper.insertAccount(account);
        Doctor doctor = new Doctor(account);
        doctorMapper.insert(doctor);
        return LayuiR.data(true, "注册成功，请重新登陆");
    }

}
